/**
 * created by 小卷毛, 2021-06-25
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.viewmodel

import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzg.extend.BaseResponse
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import com.rzico.sbl.model.AddressData
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.RegionBean
import com.xinnuo.common.extend.getJsonFromAssets
import com.xinnuo.common.manager.ContextManager
import com.xinnuo.common_ui.utils.applyFlowableSchedulers
import com.xinnuo.common_ui.utils.applySchedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

/**
 * 描 述：会员地址管理操作相关
 * 作 者：小卷毛  2021-06-25 14:30
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class AddressViewModel : CommonViewModel() {

    /**
     * 地址列表
     */
    fun adressList(memberId: String) =
        OkGo.get<BaseResponse<ArrayList<AddressData>>>(BaseUrl.addressList)
            .params(
                getParams(
                    "memberId" to memberId
                )
            )
            .converter(object : JacksonConvert<BaseResponse<ArrayList<AddressData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data }

    /**
     * 默认地址
     */
    fun adressDef(adressId: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.adressDef,
            params = getParams(
                "id" to adressId,
                "isDefault" to true
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 删除地址
     */
    fun adressDel(adressId: String) =
        RxSingleHelper.requestString(
            url = BaseUrl.adressDel,
            params = getParams("id" to adressId)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 添加地址 BaseUrl.adressAdd
     * 修改地址 BaseUrl.adressUpdate
     */
    fun adressAdd(url: String, vararg params: Pair<String, Any>) =
        RxSingleHelper.requestString(
            url = url,
            isMultipart = true,
            params = getParams(*params)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 获取省市区信息，协程流式调用
     *
     * flow上游默认线程为flow方法所处的线程
     */
    fun getAreaList(onNext: (ArrayList<RegionBean>) -> Unit) {
        viewModelScope.launch {
            flow {
                val json =
                    ContextManager
                        .instance
                        .getAppContext()
                        ?.getJsonFromAssets("province.json")
                        ?: "[]"

                emit(
                    Gson().fromJson(
                        json,
                        object : TypeToken<List<RegionBean>>() {}.type
                    ) as ArrayList<RegionBean>
                )
            }
                .flowOn(Dispatchers.Default) //切换上游线程
                .onStart { showLoading() }
                .onCompletion { dismissLoading() }
                .collect {
                    onNext.invoke(it)
                }
        }
    }

}